package goods

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gozero-demo/internal/constants"
	"gozero-demo/internal/model/dao/model"
	"gozero-demo/internal/repo/mysql"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"
	"time"
)

type GoodsEditLogic struct {
	logx.Logger
	ctx       context.Context
	svcCtx    *svc.ServiceContext
	goodsRepo *mysql.GoodsRepo
}

// 创建和编辑商品
func NewGoodsEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsEditLogic {
	return &GoodsEditLogic{
		Logger:    logx.WithContext(ctx),
		ctx:       ctx,
		svcCtx:    svcCtx,
		goodsRepo: mysql.NewGoodsRepo(ctx, svcCtx),
	}
}

func (l *GoodsEditLogic) GoodsEdit(req *types.GoodsEditRequest) (resp *types.CommonResponse, err error) {
	modelData := model.Goods{
		GoodsName:      req.GoodsName,
		GoodsAttribute: req.GoodsAttribute,
		GoodsCategory:  req.GoodsCategory,
		OriginPlace:    req.OriginPlace,
		Stock:          req.Stock,
		CostPrice:      int64(req.CostPrice * 100),
		SellingPrice:   int64(req.SellingPrice * 100),
		Status:         req.Status,
		UpdateTime:     time.Now(),
	}

	if req.Id == 0 { // 创建商品
		modelData.CreateTime = time.Now()
		modelData.IsDeleted = constants.IsDeletedNo
		_, err = l.goodsRepo.CreateGoods(&modelData)
	} else { // 编辑商品
		_, err = l.goodsRepo.UpdateGoods(&modelData, req.Id)
	}
	if err != nil {
		return nil, err
	}

	return types.SuccessResponseEmpty(l.ctx), nil
}
